﻿using System;
using System.Linq;
using VideoSeller.Business.Data;
using VideoSeller.Business.Data.Enums;
using VideoSeller.Core.Configuration;

namespace VideoSeller.Business.Models
{
	public class FinanceModel : Repository<Finance>
	{
		public void UpdateTotal(Guid userId, decimal value, FinanceOperation operation)
		{
			var finance = Table.SingleOrDefault(x => x.UserId == userId);

			if (finance != null)
			{
				switch (operation)
				{
					case FinanceOperation.Refill:
					case FinanceOperation.OnlineContentRecharge:
					case FinanceOperation.AdministratorAdd:
					case FinanceOperation.RefundForIllegalContent:
						finance.Total += Math.Abs(value);
						break;
					case FinanceOperation.OnlineContentAdvertisingPayment:
					case FinanceOperation.OnlineContentPayment:
					case FinanceOperation.AdministratorSubstract:
					case FinanceOperation.WithdrawCompleted:
					case FinanceOperation.WithdrawCompletedPartial:
					case FinanceOperation.SubstractForIllegalContent:
                    case FinanceOperation.BroadcastPayment:
						finance.Total -= Math.Abs(value);
						break;
				}
			}

			SubmitAllChanges();
		}

		public void AddClientFinance(Client client)
		{
			var finance = new Finance
				{
					UserId = client.UserId,
					Total = 0,
					Active = true
				};
			Insert(finance);
		}

		public void BlockUnblock(Guid userId, bool isBlock)
		{
			var finance = Table.SingleOrDefault(x => x.UserId == userId);

			if (finance != null)
			{
				finance.Active = !isBlock;
			}

			SubmitAllChanges();
		}

		public void DeleteFinance(Guid userId)
		{
			var finance = Table.SingleOrDefault(x => x.UserId == userId);

			if (finance != null)
			{
				var paidModel = IoC.Resolve<PaidModel>();
				var postingModel = IoC.Resolve<PostingModel>();
				paidModel.DeleteAll(finance.Paids);
				postingModel.DeleteAll(finance.Postings);
				Delete(finance);
			}
		}
	}
}